%% Author: 77
%% Created: 2011-7-6
%% Description: TODO: Add description to create_vm_cmd
-module(create_vm_cmd).
-author(kanghua ).  
-email(kanghua151@msn.com).  
-date("2011.07.06").  
%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([handle/3]).

%%
%% API Functions
%%
handle(Content,From,State) ->
	io:format("handle info ~p ~p ~p ~p ~n",[?MODULE,Content,From,State]), %% debug info
	case check_parm(Content) of
		 true -> 
			 io:format("check parm pass ~n"),
		     {VcpuCount,MemSize,DiskSize} = Content,
			 io:format("request info ~p ~p ~p ~n",[VcpuCount,MemSize,DiskSize]), %% debug info
			 case meta_data_ops:request_network_address_resource() of
				  {IpAddr,MacAddr}->
        			  io:format("ip ,mac ~p ~p ~n",[IpAddr,MacAddr]), %% debug info
					  % eg:VncPort=5901,VncPass="123456",  %% debug info
					  VncPort=vncport:get_next_vncport(),
%					  VncPort=5901,
					  io:format("fanyingfei~n"),
					  VncPass=password:get_vnc_password(),
			 		  VmId=sequence:get_next_sequence(vm_id),
             		  io:format("new vm id ~p ~n",[VmId]), %% debug info
					  VmUser="openday",
					  VmUserPass="123456", %% master allocate
                      case meta_data_ops:request_node_resource(MemSize,DiskSize) of 
                           Node ->
                              case gen_server:call({node_server,list_to_atom(Node)},{create_vm,{VcpuCount,MemSize,DiskSize,IpAddr,MacAddr,VncPass,VncPort,VmUser,VmUserPass,VmId}},1000) of
                                   {error,Reason} -> 
                                        meta_data_ops:return_node_resource(Node,MemSize,DiskSize),
                                        meta_data_ops:return_network_address_resource(IpAddr,MacAddr),
                                        gen_server:reply(From,{error,no_sys_resource}),
                                        false;
                                   ok-> 
                                        meta_data_ops:insert_vm_resource_config(VmId,VcpuCount,MemSize,DiskSize,IpAddr,"None"),
		     							HostName = Node,
%			 							meta_data_ops:insert_vm_runtime_info(VmId,HostName,stopped),
			 							meta_data_ops:insert_vm_runtime_info(VmUser,HostName,stopped),
			 							gen_server:reply(From,{ok,VmUser}),
                                        ok
                              end
                      end;              
				  false -> 
                      gen_server:reply(From,{error,no_network_resource}),
                      false
              end;
		 false -> 
			 gen_server:reply(From,{error,err_param}),
             false
    end.

%%
%% Local Functions
%%

check_parm(Content)->
	true.
